import { defineStore } from "pinia";
import { ref, computed } from "vue";
import api, { authAPI } from "../services/api";

interface User {
  id: number;
  username: string;
  email?: string;
  avatar?: string;
  createdAt: string;
}

interface AuthResponse {
  user: User;
  token: string;
}

export const useAuthStore = defineStore("auth", () => {
  const user = ref<User | null>(null);
  const token = ref<string | null>(localStorage.getItem("token"));

  const isAuthenticated = computed(() => !!token.value && !!user.value);

  // 设置axios默认配置
  if (token.value) {
    api.defaults.headers.common["Authorization"] = `Bearer ${token.value}`;
  }

  async function login(username: string, password: string) {
    try {
      const response = await authAPI.login(username, password);

      const { user: userData, token: tokenData } = response.data;

      user.value = userData;
      token.value = tokenData;

      localStorage.setItem("token", tokenData);
      api.defaults.headers.common["Authorization"] = `Bearer ${tokenData}`;

      return { success: true };
    } catch (error: any) {
      return {
        success: false,
        error: error.response?.data?.message || "登录失败",
      };
    }
  }

  async function register(username: string, password: string, email?: string) {
    try {
      const response = await authAPI.register(username, password, email);

      const { user: userData, token: tokenData } = response.data;

      user.value = userData;
      token.value = tokenData;

      localStorage.setItem("token", tokenData);
      api.defaults.headers.common["Authorization"] = `Bearer ${tokenData}`;

      return { success: true };
    } catch (error: any) {
      return {
        success: false,
        error: error.response?.data?.message || "注册失败",
      };
    }
  }

  async function logout() {
    try {
      if (token.value) {
        await authAPI.logout();
      }
    } catch (error) {
      console.error("登出错误:", error);
    } finally {
      user.value = null;
      token.value = null;
      localStorage.removeItem("token");
      delete api.defaults.headers.common["Authorization"];
    }
  }

  async function fetchProfile() {
    try {
      const response = await authAPI.getProfile();
      user.value = response.data;
      return { success: true };
    } catch (error: any) {
      return {
        success: false,
        error: error.response?.data?.message || "获取用户信息失败",
      };
    }
  }

  return {
    user,
    token,
    isAuthenticated,
    login,
    register,
    logout,
    fetchProfile,
  };
});
